<template>
  <div id="uploadeFiles">
    <el-upload
      ref="upload"
      action="#"
      :http-request="() => {}"
      :on-exceed="handleExceed"
      :limit="limit"
      :accept="accept"
      :file-list="fileList"
      :before-upload="handlerChange"
      :show-file-list="false"
      multiple
    >
      <el-button v-if="isShow" slot="trigger" size="small" type="success"
        >选取文件</el-button
      >
    </el-upload>
    <!-- 附件列表 -->
    <div class="attachmentList">
      <div
        class="attachmentList-item"
        v-for="(item, index) in fileList"
        :key="index"
      >
        <img
          v-if="isPackage(item.name)"
          src="@assets/img/fileType-package.svg"
          alt=" "
        />
        <img
          v-if="isPicture(item.name)"
          src="@assets/img/fileType-picture.svg"
          alt=" "
        />
        <img
          v-if="isVideo(item.name)"
          src="@assets/img/fileType-video.svg"
          alt=" "
        />
        <div class="detail">
          <div class="fileName">{{ item.name }}</div>
          <div class="handle">
            <el-button
              type="text"
              @click="handlePreview(item)"
              class="preview-color"
              v-if="isPreview(item.name)"
              >预览</el-button
            >
            <el-button
              type="text"
              v-if="isShow"
              @click="handleDelete(item)"
              class="delete-color"
              >删除</el-button
            >
            <el-button type="text" v-else @click="downloadFile(item)"
              >下载</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 上传说明 -->
    <div class="el-upload__tip">
      <p>支持上传的附件：</p>
      <p>1、图片：支持png、 jpg、gif、 jpeg等格式；</p>
      <p>2、视频：支持MP4、WebM、Ogg等格式；</p>
      <p>3、压缩包：支持ZIP、RAR格式；</p>
    </div>
    <!-- 图片预览 -->
    <elImageViewer
      v-if="imgViewerVisible"
      :on-close="closeImgViewer"
      :url-list="showViewerPicList"
    />
    <!-- 视频预览 -->
    <el-dialog
      title="视频播放预览"
      width="800px"
      :visible.sync="videoData.isShow"
      :before-close="handleClose"
      :modal="false"
    >
      <video
        class="videoView"
        ref="video"
        :src="videoData.videoUrl"
        controls
        autoplay
        loop
      >
        你的浏览器不能支持HTML5视频
      </video>
    </el-dialog>
  </div>
</template>
<script>
import { uploadAccessory } from '@/api/notice'
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
import { funDownload } from '@/utils/deal-blob'
export default {
  name: 'UploadeFiles',
  components: {
    elImageViewer
  },
  props: {
    //文件列表
    filesList: {
      type: Array,
      default: function() {
        return []
      }
    },
    //允许上传最大文件个数
    limit: {
      type: Number,
      default: function() {
        return 5
      }
    },
    //单个文件大小
    fileSize: {
      type: Number,
      default: function() {
        return 10
      }
    },
    //总文件大小
    fileAllSize: {
      type: Number,
      default: function() {
        return 50
      }
    },
    //可上传文件类型
    accept: {
      type: String,
      default: function() {
        return '.jpg, .jpeg, .png, .gif, .mp4, .zip, .rar'
      }
    },
    //隐藏上传按钮
    isShow: {
      type: Boolean,
      default: function() {
        return true
      }
    }
  },
  data() {
    return {
      loading: false,
      collect: false,
      imgViewerVisible: false,
      fileList: [],
      showViewerPicList: [],
      videoData: {
        isShow: false,
        videoUrl: '#'
      }
    }
  },
  watch: {
    filesList: {
      handler(val) {
        this.fileList = val
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    //文件改变时
    handlerChange(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'))
      if (this.accept.indexOf(fileSuffix) === -1) {
        this.$message.warning(`不支持上传${fileSuffix}类型文件`)
        return false
      }
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error(
          `单文件最大不可超过${this.fileSize}M,请检查 “${file.name}” 文件大小`
        )
        return
      }
      this.submitUpload(file)
    },
    //上传
    submitUpload(file) {
      let formData = new FormData()
      formData.append('file', file)
      uploadAccessory(
        formData,
        (response) => {
          this.loading = false
          this.$emit('getFilesUrl', response)
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )
    },
    //删除
    handleDelete(val) {
      this.$confirm(`是否删除${val.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$emit('deleteFile', val.uid)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    //限制文件个数
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制上传 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，现已有 ${fileList.length} 个文件`
      )
    },
    //预览
    handlePreview(file) {
      let url = file.url
      const suffix = file.name
        .substring(file.name.lastIndexOf('.'))
        .toLowerCase()
      const imgType = '.png, .jpg, .jpeg, .gif'
      const videoType = '.mp4, .webm, .ogg'
      if (imgType.includes(suffix)) {
        let arr = []
        arr.push(url)
        this.imgViewerVisible = true
        this.showViewerPicList = arr
      } else if (videoType.includes(suffix)) {
        if (!url) {
          this.$message.warning('无视频资源！')
          return
        }
        this.videoData.isShow = true
        this.$nextTick(() => {
          this.videoData.videoUrl = url
        })
      }
    },
    //下载
    downloadFile(file) {
      funDownload(file.url, file.name)
    },
    //关闭图片预览
    closeImgViewer() {
      this.imgViewerVisible = false
    },
    //关闭视频预览
    handleClose() {
      this.videoData.videoUrl = ''
      this.videoData.isShow = false
    },
    //附件类型图片
    fileTypePic(fileName, fileType) {
      const suffix = fileName.substring(fileName.lastIndexOf('.'))
      return fileType.includes(suffix)
    }
  },
  computed: {
    isPackage() {
      return function(fileName) {
        const fileType = '.zip, .rar'
        return this.fileTypePic(fileName, fileType)
      }
    },
    isPicture() {
      return function(fileName) {
        const fileType = '.png, .jpg, .jpeg, .gif'
        return this.fileTypePic(fileName, fileType)
      }
    },
    isVideo() {
      return function(fileName) {
        const fileType = '.mp4, .webm, .ogg'
        return this.fileTypePic(fileName, fileType)
      }
    },
    isPreview() {
      return function(fileName) {
        const fileType = '.zip, .rar'
        return !this.fileTypePic(fileName, fileType)
      }
    }
  }
}
</script>

<style lang="less" scope>
#uploadeFiles {
  .videoView {
    width: 800px;
    height: 500px;
    background: #000;
  }
  .el-dialog__body {
    padding: 0 !important;
  }
  .el-upload__tip {
    p {
      height: 16px;
    }
  }
  .attachmentList {
    display: flex;
    flex-wrap: wrap;
    width: 550px;
    .attachmentList-item {
      width: 160px;
      height: 45px;
      display: flex;
      align-items: flex-start;
      .el-icon-document {
        font-size: 40px;
        height: 100%;
        line-height: 45px;
      }
      .detail {
        display: flex;
        flex-direction: column;
        font-size: 12px;
        .fileName {
          width: 90px;
          height: auto;
          margin-top: -8px;
          display: -webkit-box;
          overflow: hidden; /*超出隐藏*/
          text-overflow: ellipsis; /*隐藏后添加省略号*/
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1; //想显示多少行
        }
        .handle {
          height: 12px;
          margin-top: -20px;
          .preview-color {
            cursor: pointer;
            color: #1dc8a4;
          }
          .delete-color {
            cursor: pointer;
            color: red;
          }
        }
        span {
          margin-right: 10px;
        }
      }
      img {
        margin: 5px 5px 0 0;
        height: 35px;
      }
    }
  }
}
</style>
